<template>
  <div class="page-wrapper">
    <div class="page-body">
      <div class="container-xl">
        <div class="row row-deck row-cards">
          <div class="col-12">
            <div class="card">
              <div class="card-header">
                <h3 class="card-title">Token 管理</h3>
                <div class="card-actions">
                  <button class="btn btn-primary" @click="handleAdd">
                    <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-plus" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
                      <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                      <path d="M12 5l0 14"></path>
                      <path d="M5 12l14 0"></path>
                    </svg>
                    新增Token
                  </button>
                </div>
              </div>
              <div class="card-body border-bottom py-3">
                <div class="d-flex">
                  <div class="text-secondary">
                    {{ tableData ? tableData.length : 0 }} 条记录
                  </div>
                  <div class="ms-auto text-secondary">
                    搜索:
                    <div class="ms-2 d-inline-block">
                      <input type="text" 
                             class="form-control form-control-sm" 
                             v-model="searchQuery"
                             placeholder="请输入工号或简码"
                             @input="handleSearch">
                    </div>
                  </div>
                </div>
              </div>
              <div class="card-body">
                <div class="table-responsive">
                  <table class="table table-vcenter card-table">
                    <thead>
                      <tr>
                        <th>用户工号</th>
                        <th>标志简码</th>
                        <th>描述</th>
                        <th>创建人</th>
                        <th>创建时间</th>
                        <th>更新时间</th>
                        <th>校验码Token</th>
                        <th class="w-1">操作</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="item in filteredData" :key="item.id">
                        <td>{{ item.employeeId }}</td>
                        <td>{{ item.code }}</td>
                        <td>{{ item.description }}</td>
                        <td>{{ item.creator }}</td>
                        <td>{{ item.createTime }}</td>
                        <td>{{ item.updateTime }}</td>
                        <td>
                          <div class="d-flex align-items-center">
                            <span class="text-secondary me-2">{{ item.verifyCode }}</span>
                            <button class="btn btn-sm btn-outline-primary" 
                                    @click="handleRefreshToken(item)"
                                    :disabled="!canRefreshToken(item)">
                              刷新
                            </button>
                          </div>
                        </td>
                        <td>
                          <div class="btn-list flex-nowrap">
                            <button class="btn btn-primary btn-sm" @click="handleEdit(item)">
                              编辑
                            </button>
                            <button class="btn btn-danger btn-sm" @click="handleDelete(item)">
                              删除
                            </button>
                          </div>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 新增/编辑对话框 -->
  <div class="modal modal-blur fade" id="tokenModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">{{ isEdit ? '编辑Token' : '新增Token' }}</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form id="tokenForm" class="needs-validation" novalidate>
            <div class="mb-3">
              <label class="form-label required">用户工号</label>
              <input type="text" 
                     class="form-control" 
                     v-model="formData.employeeId"
                     :disabled="isEdit"
                     required>
            </div>
            <div class="mb-3">
              <label class="form-label required">标志简码</label>
              <input type="text" 
                     class="form-control" 
                     v-model="formData.code"
                     :disabled="isEdit"
                     required>
            </div>
            <div class="mb-3">
              <label class="form-label required">描述</label>
              <textarea class="form-control" 
                        v-model="formData.description"
                        rows="3"
                        required></textarea>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-link link-secondary" data-bs-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary ms-auto" @click="handleSave">保存</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 删除确认对话框 -->
  <div class="modal modal-blur fade" id="deleteModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">确认删除</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          确定要删除这条Token记录吗？
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-link link-secondary" data-bs-dismiss="modal">取消</button>
          <button type="button" class="btn btn-danger ms-auto" @click="confirmDelete">确定删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { Modal } from 'bootstrap';
import demoList from '@/data/demoList.json';

const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
const tableData = ref([]);
const searchQuery = ref('');
const isEdit = ref(false);
const formData = ref({
  employeeId: '',
  code: '',
  description: ''
});
const currentItem = ref(null);
const tokenModal = ref(null);
const deleteModal = ref(null);

// 过滤后的数据
const filteredData = computed(() => {
  if (!tableData.value) return [];
  if (!searchQuery.value) return tableData.value;
  
  const query = searchQuery.value.toLowerCase();
  return tableData.value.filter(item => 
    item.employeeId.toLowerCase().includes(query) ||
    item.code.toLowerCase().includes(query)
  );
});

// 获取数据
const fetchData = async () => {
  try {
    tableData.value = demoList.list;
  } catch (error) {
    console.error('Error fetching demo data:', error);
  }
};

// 处理搜索
const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
};

// 处理新增
const handleAdd = () => {
  isEdit.value = false;
  formData.value = {
    employeeId: '',
    code: '',
    description: ''
  };
  tokenModal.value.show();
};

// 处理编辑
const handleEdit = (item) => {
  isEdit.value = true;
  currentItem.value = item;
  formData.value = {
    employeeId: item.employeeId,
    code: item.code,
    description: item.description
  };
  tokenModal.value.show();
};

// 处理保存
const handleSave = async () => {
  const form = document.getElementById('tokenForm');
  if (!form.checkValidity()) {
    form.classList.add('was-validated');
    return;
  }

  try {
    if (isEdit.value) {
      // 编辑逻辑
      const index = tableData.value.findIndex(item => item.id === currentItem.value.id);
      if (index !== -1) {
        tableData.value[index] = {
          ...tableData.value[index],
          description: formData.value.description,
          updateTime: new Date().toLocaleString()
        };
      }
    } else {
      // 新增逻辑
      const newToken = {
        id: tableData.value.length + 1,
        employeeId: formData.value.employeeId,
        code: formData.value.code,
        description: formData.value.description,
        creator: '当前用户', // 实际应从用户系统获取
        createTime: new Date().toLocaleString(),
        updateTime: new Date().toLocaleString(),
        verifyCode: generateToken(formData.value.employeeId, formData.value.code),
        lastRefreshTime: null
      };
      tableData.value.push(newToken);
    }
    tokenModal.value.hide();
  } catch (error) {
    console.error('Error saving token:', error);
  }
};

// 处理删除
const handleDelete = (item) => {
  currentItem.value = item;
  deleteModal.value.show();
};

// 确认删除
const confirmDelete = async () => {
  try {
    const index = tableData.value.findIndex(item => item.id === currentItem.value.id);
    if (index !== -1) {
      tableData.value.splice(index, 1);
    }
    deleteModal.value.hide();
  } catch (error) {
    console.error('Error deleting token:', error);
  }
};

// 处理刷新Token
const handleRefreshToken = async (item) => {
  if (!canRefreshToken(item)) return;
  
  try {
    const index = tableData.value.findIndex(i => i.id === item.id);
    if (index !== -1) {
      tableData.value[index] = {
        ...tableData.value[index],
        verifyCode: generateToken(item.employeeId, item.code),
        lastRefreshTime: new Date().toISOString(),
        updateTime: new Date().toLocaleString()
      };
    }
  } catch (error) {
    console.error('Error refreshing token:', error);
  }
};

// 检查是否可以刷新Token
const canRefreshToken = (item) => {
  if (!item.lastRefreshTime) return true;
  const lastRefresh = new Date(item.lastRefreshTime);
  const now = new Date();
  const hoursDiff = (now - lastRefresh) / (1000 * 60 * 60);
  return hoursDiff >= 24;
};

// 生成Token
const generateToken = (employeeId, code) => {
  const date = new Date();
  const dateStr = date.getFullYear().toString().substr(1) + 
                 (date.getMonth() + 1).toString().padStart(2, '0') + 
                 date.getDate().toString().padStart(2, '0');
  const uuid = Math.random().toString(36).substring(2, 15);
  return `N${dateStr}_${uuid}`;
};

onMounted(() => {
  fetchData();
  tokenModal.value = new Modal(document.getElementById('tokenModal'));
  deleteModal.value = new Modal(document.getElementById('deleteModal'));
});
</script>

<style scoped>
.bg-green-lt {
  background-color: rgba(40, 167, 69, 0.15) !important;
  color: #2fb344 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

.bg-red-lt {
  background-color: rgba(220, 53, 69, 0.15) !important;
  color: #d63939 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

/* 表格列宽优化 */
.table th:nth-child(1) { width: 120px; }  /* 用户工号列 */
.table th:nth-child(2) { width: 120px; }  /* 标志简码列 */
.table th:nth-child(3) { width: 200px; }  /* 描述列 */
.table th:nth-child(4) { width: 100px; }  /* 创建人列 */
.table th:nth-child(5) { width: 160px; }  /* 创建时间列 */
.table th:nth-child(6) { width: 160px; }  /* 更新时间列 */
.table th:nth-child(7) { width: 200px; }  /* 校验码Token列 */
.table th:nth-child(8) { width: 120px; }  /* 操作列 */

/* 必填项样式 */
.required:after {
  content: " *";
  color: red;
}

/* 表单验证样式 */
.was-validated .form-control:invalid {
  border-color: #dc3545;
  padding-right: calc(1.5em + 0.75rem);
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right calc(0.375em + 0.1875rem) center;
  background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}

.was-validated .form-control:valid {
  border-color: #198754;
  padding-right: calc(1.5em + 0.75rem);
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23198754' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right calc(0.375em + 0.1875rem) center;
  background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}
</style> 